// pages/receiving-address/receiving-address.js
import { getReceiveAddress, setDefaultAddress, deleteReceiveAddress } from '../../api/apis.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    color: '#ED204F',
    checked: true,
    addressList: [{
      name: '张珊',
      tel: '15735409512',
      address: '江苏省南京市栖霞区栖霞街110号'
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      noback: options.noback?true:false
    })
    this._initData()
  },
  onShow(){
    this._initData()
  },
  _initData(){
    getReceiveAddress({
      data: {
        openid: app.globalData.openid
      },
      success: res => {
        if (res.state) {
          this.setData({
            addressList: res.data
          })
        }
      }
    })
  },
  setDefault(e) {
    setDefaultAddress({
      data: {
        openid: app.globalData.openid,
        id: e.currentTarget.dataset.item.mid
      },
      success: res => {
        if (res.state) {
          this._initData()
        }
      }
    })
  },
  deletAddress(e) {
    wx.showModal({
      title: '',
      content: '确定删除此地址？',
      success: res => {
        if (res.confirm) {
          deleteReceiveAddress({
            data: {
              openid: app.globalData.openid,
              id: e.currentTarget.dataset.item.mid
            },
            success: res => {
              if (res.state) {
                this._initData()
              }
            }
          })
        }
      }
    })
  },
  editAddress(e) {
    wx.navigateTo({
      url: `../build-address/build-address?did=${e.currentTarget.dataset.item.mid}`,
    })
  },
  setAddress(e) {
    wx.setStorage({
      key: 'address',
      data: e.currentTarget.dataset.item,
      success: res => {
        if (!this.data.noback){
          wx.navigateBack({
            delta: 1
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})